const config = require("../config.js");
const {mysqlService} = require("./mysqlService.js");
let normalResult = require("../normalResult.js")
let result = JSON.parse(normalResult)

const baseModel = {
    getAll: async (sql) => {
        try {
            result = Object.assign(result, config.result.success)
            result.data = await mysqlService(sql, []);
        } catch (error) {
            result = Object.assign(result, config.result.error)
        }
        return result
    },

    // sql示例：select id, name, price from mo_goods
    getDataById: async (sql, id) => {
        sql += ` where id = ${id}`
        try {
            let res = await mysqlService(sql, []);
            if (res.length) {
                result.data = res[0];
            } else {
                result = Object.assign(result, config.result.notData)
            }
            return result;
        } catch (error) {
            result = Object.assign(result, config.result.sqlError)
            return result
        }
    },

    add: async (table, data, connection) => {
        if (data.id) delete data.id;
        const keys = Object.keys(data);
        const values = Object.values(data);
        const placeholders = keys.map(() => '?').join(',');
        const sql = `INSERT INTO ${table} (${keys.join(',')})
                     VALUES (${placeholders})`;
        let res = null
        if (connection) {
            res = await mysqlService(sql, values, connection);
            return res
        } else {
            try {
                res = await mysqlService(sql, values);
                result = Object.assign(result, res)
                result.data = res.insertId;
                return result;
            } catch (error) {
                result = Object.assign(result, config.result.sqlError)
                return result
            }
        }
    },

    updateById: async (table, params, connection) => {
        let data = {}
        let id = 0
        if (params.id) {
            id = params.id
            delete params.id
            data = Object.assign({}, params)
        } else {
            result = Object.assign(result, config.result.missingPrimaryError);
            return result
        }
        let sql = `update ${table}`
        sql += ' set '
        for (let key in data) {
            sql += `${key} = '${data[key]}',`
        }
        sql = sql.substring(0, sql.length - 1);
        sql += ` where id = ${id}`
        if (connection) {
            await mysqlService(sql, [], connection);
        } else {
            try {
                await mysqlService(sql, []);
                result = Object.assign(result, config.result.success)
                return result;
            } catch (error) {
                result = Object.assign(result, config.result.sqlError)
                return result
            }
        }
        result.data = id;
        return result;
    },

    // let totalSql = "SELECT COUNT(*) AS total FROM mo_goods";
    // let sql = 'select id, name, price from mo_goods';
    getPagination: async (sql, totalSql, page, size) => {
        page = parseInt(page) || 1;
        size = parseInt(size) || 10;
        const offset = (page - 1) * size;
        try {
            result = Object.assign(result, config.result.success)
            sql = `${sql} limit ?, ?`;
            result.data = await mysqlService(sql, [offset, size]);
            if (totalSql) {
                const t = await mysqlService(totalSql, []);
                result.total = t[0].total || 0;
            }
            return result
        } catch (error) {
            result = Object.assign(result, config.result.operationError)
            return result
        }
    },

    realDelById: async (table, id) => {
        let sql = 'delete from ' + table + ' where id = ' + id;
        try {
            let res = await mysqlService(sql, []);
            if (res.affectedRows) {
                result.msg = '删除成功'
                result.data = id
                return result
            } else {
                result = Object.assign(result, config.result.notData)
                return result
            }
        } catch (error) {
            result = Object.assign(result, config.result.error)
            return result
        }
    },

};

module.exports = {
    baseModel: baseModel
}
